package com.zxn.service;

import com.zxn.utils.ElasticUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.suggest.*;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.elasticsearch.search.suggest.term.TermSuggestionBuilder;

import java.util.ArrayList;
import java.util.List;

/**
 * program: springbootelastic
 * description: ${description}
 * author: zxn
 * create: 2019-04-07 19:28
 **/
public class IkAnalyzer {

    public static  List<String> suggestForIkSmart(String prefix) {
        SuggestBuilder suggestion = new SuggestBuilder();
        suggestion.addSuggestion("suggesttags",SuggestBuilders.completionSuggestion("suggesttag").text(prefix));
        SearchResponse response = ElasticUtils.getClient().prepareSearch("suggestindex").setTypes("suggesttest").suggest(suggestion).execute().actionGet();
        Suggest suggest = response.getSuggest();
        // 没有任何数据
        if (suggest == null) {
            return new ArrayList<String>();
        }
        List<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> list = response.getSuggest().getSuggestion("suggesttags").getEntries();
        List<String> suggestList = new ArrayList<String>();
        if (list == null) {
            return null;
        } else {
            for (Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option> e : list) {
                for (Suggest.Suggestion.Entry.Option option : e) {
                    suggestList.add(((CompletionSuggestion.Entry.Option) option).getHit().getSourceAsString());
                }
            }
        }
        return suggestList;
    }

    public static void main(String[] args) {
        List<String> result = suggestForIkSmart("pinying");
        for (String str : result) {
            System.out.println(str);
        }
    }
}
